package userlogic

import (
	"common/comCopier"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"
	"time"

	"OemServer/internal/svc"
	"OemServer/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.User) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.NickName == "" {
		return nil, errors.New("nickName is null")
	}
	if in.Account == "" {
		return nil, errors.New("account is null")
	}
	if in.RoleUUID == "" {
		return nil, errors.New("RoleUUID is null")
	}

	var (
		user = model.User{}
	)
	user.Password = "123456"
	if err := comCopier.CopyWithOption(&user, in); err != nil {
		return nil, err
	}
	user.UUID = utils.GetUuid()
	t := time.Now()
	user.CreateTime = &t
	db := l.svcCtx.DB
	table := db.Table(model.TableNameUser)
	err := table.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&user).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
